﻿@{
    ViewBag.Title = "AddProduct";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}
<script src="~/Areas/Admin/Content/kindeditor/kindeditor-min.js"></script>
<script src="~/Areas/Admin/Content/plupload/moxie.min.js"></script>
<script src="~/Areas/Admin/Content/plupload/plupload.full.min.js"></script>
<link href="~/Areas/Admin/Content/docs.css" rel="stylesheet" />
@model ProductModel
<div style="text-align: center; color: red">@TempData["Result"]</div>
<div class="row-fluid" style="margin-bottom: 150px;">
    <div class="span24 span-first">
        <form id="AddForm" class="form-horizontal" method="post" action="/Admin/Product/EditProduct">
            @Html.HiddenFor(x => x.Product.ID)
            @Html.AntiForgeryToken()
            <div class="demo-content">
                <div id="tab"></div>
                <div class="row">
                    <div class="span22 bordered">
                        <div style="padding: 20px">
                            <div id="ProductInfo">
                                <div class="control-group">
                                    <label class="control-label"><s>*</s>类别：</label>
                                    <div class="controls">
                                        <div id="Product_ClassName" style="width: 350px">
                                            @Html.HiddenFor(x => x.Product.ClassID)
                                        </div>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label"><s>*</s>产品名称：</label>
                                    <div class="controls">
                                        @Html.TextBoxFor(x => x.Product.PName, new { datarules = "{required:true}", style = "width:350px" })
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label"><s>*</s>型号：</label>
                                    <div class="controls">
                                        @Html.TextBoxFor(x => x.Product.PModel, new {  datarules = "{required:true}",style = "width:350px" })
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label"><s>*</s>价格：</label>
                                    <div class="controls">
                                        @Html.TextBoxFor(x => x.Product.PPrice, new { datarules = "{required:true}", style = "width:350px" })
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label" style="height: 192px;">标题图片：</label>
                                    <div class="controls" style="height: 192px;">
                                        <span id="uploadTitleBtn" class="x-icon x-icon-success">+</span>
                                        <div id="uploadTitleDiv" style="width: 150px; height: 150px; border: 1px solid #c3c3d6"></div>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label" style="height: 114px">产品简介：</label>
                                    <div class="controls">
                                        @Html.TextAreaFor(x => x.Product.Introduction, new { style = "height:100px;width:732px" })
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label" style="height: 314px">产品介绍：</label>
                                    <div class="controls" style="height: 314px">
                                        @Html.TextAreaFor(x => x.Product.Description, new { @class = "ckeditor", style = "height:300px;width:740px" })
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label" style="height: 470px">
                                        图片组：</label>
                                    <div class="controls" style="height: 470px">
                                        <span id="uploadBtn" class="x-icon x-icon-success">+</span>
                                        <div id="ImgGroup" style="width: 730px; padding: 5px; overflow: auto; height: 418px; overflow: auto; border: 1px solid #c3c3d6">
                                        </div>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label">状态：</label>
                                    <div class="controls">
                                        <label>@Html.RadioButtonFor(x => x.Product.Status, "10", new { @checked = "checked" }) 审核通过</label>
                                        <label>@Html.RadioButtonFor(x => x.Product.Status, "20") 待审核</label>
                                    </div>
                                </div>
                                <div class="control-group">
                                    <label class="control-label"><s>*</s>发布日期：</label>
                                    <div class="controls">
                                        @Html.TextBoxFor(x => x.Product.AddDate, new { @class = "calendar", style = "width:150px" })
                                    </div>
                                </div>
                            </div>
                            <div id="OtherInfo">
                                <div style="margin-bottom: 10px">
                                    <input type="hidden" id="ProID" />
                                    <span>属性名称：<input type="text" id="ProText" data_rules="{required : true}" /></span>
                                    <span>属性值：<input type="text" id="ProValue" data_rules="{required : true}" style="width: 300px" /></span>
                                    <span>排序：<input type="text" id="ProSort" data_rules="{required : true , number : true}" style="width: 60px" /></span>
                                    <button class="button button-small" id="AddProBtn" type="button">添加</button>
                                </div>
                                <div id="OtherInfoGrid"></div>
                                <div id="ProDiv" style="display: none"></div>
                            </div>
                            <hr>
                            <div id="submitDiv" style="text-align: center">
                                <button id="submitBtn" class="button button-primary" type="submit">提交</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
<script type="text/javascript">

    KindEditor.ready(function (K) {
        K.create('#Product_Description', {
            uploadJson: '/Account/Upload',
            resizeType: 0,
            //fileManagerJson: '/Account/Upload',
            allowFileManager: false,
            items: [
        'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'insertfile', 'table', 'hr', 'emoticons', 'pagebreak',
        'anchor', 'link', 'unlink', '|', 'about'
            ]
        });
    });

    var validForm = null;
    var validGroups = {};
    var List = BUI.List;
    var store = null;
    var tpl = [
   '<li class="bui-list-item">',
     '<div class="img-list-content">',
       '<a class="img-list-link" href="{href}">',
         '<img src="{src}"/>',
       '</a>',
       '<div class="img-list-des">',
         '<div>标题：<input type="text" value="{title}"/><input type="hidden" value="{id}"/><span onclick="RemoveImgItem(\'{id}\')" class="x-icon x-icon-mini x-icon-hover img-list-item-close">×</span></div>',
         '<div class="img-list-pro">描述：<textarea class="img-list-item-des">{desc}</textarea></div>',
         '<div>排序：<input type="text" value="{sort}"/></div>',
       '</div>',
     '</div>',
     '<div class="img-list-border">',
     '</div>',
   '</li>'
    ];
    list = new List.SimpleList({
        render: '#ImgGroup',
        idField: 'id',
        elCls: 'img-list clearfix',
        items: [],
        itemTpl: tpl.join('')
    });
    list.render();
    function RemoveImgItem(id) {
        if (confirm('确定删除？')) {
            var item = list.getItem(id);
            list.removeItem(item);
            if (validGroups[id])
                delete validGroups[id];
        }
    }
    var uploader = new plupload.Uploader({
        runtimes: 'flash',
        browse_button: 'uploadBtn', // you can pass in id...
        //container: document.getElementById('container'), // ... or DOM Element itself
        url: "/FileUpload/AjaxUploadFile",
        filters: {
            max_file_size: '10mb',
            mime_types: [
                { title: "Image files", extensions: "jpg,jpeg,gif,png" }
                //{ title: "Zip files", extensions: "zip,rar" }
            ]
        },
        flash_swf_url: '../../../Areas/Admin/Content/plupload/Moxie.swf',
        //silverlight_xap_url: 'http://rawgithub.com/moxiecode/moxie/master/bin/silverlight/Moxie.cdn.xap',
        init: {
            PostInit: function () {

            },
            FilesAdded: function (up, files) {
                uploader.start();
                //var file = files[0];
                //var img = new o.Image();
                //img.onload = function () {
                //    img.embed($('#imgdiv')[0], {
                //        width: 100,
                //        height: 60,
                //        crop: true,
                //        swf_url: o.resolveUrl(up.settings.flash_swf_url),
                //        xap_url: o.resolveUrl(up.settings.silverlight_xap_url)
                //    });
                //};
                //img.load(file.getSource());
            },
            UploadProgress: function (up, file) {
                //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            },
            FileUploaded: function (up, file, info) {
                var res = '{}';
                if (info.response == null) {
                    var headers = info.responseHeaders.split('\r\n');
                    $.each(headers, function (n, item) {
                        if (item && item.split(':')[0] == 'res') {
                            res = eval('(' + item.split(':')[1] + ')');
                        }
                    })
                } else {
                    res = eval('(' + info.response + ')');
                }
                if (res.result == true) {
                    list.addItem({
                        id: res.id,
                        title: '',
                        sort: '0',
                        href: 'javascript:void(0);',
                        src: '/File/' + res.id,
                        desc: ''
                    });
                    $('.img-list-des').last().find('input').last().attr('data-rules', '{required:true,number:true}');
                    var valid = new BUI.Form.Group({ //创建表单分组，此分组不在表单form对象中，所以不影响校验
                        srcNode: $('.img-list-des').last(),
                        elCls: '',
                        errorTpl: '<span class="x-icon x-icon-small x-icon-error" data-title="{error}">!</span>',
                        showError: false,
                        defaultChildCfg: {
                            elCls: ''
                        }
                    }).render();
                    validGroups[res.id] = valid;
                    //不使用模板的，左侧显示
                    new BUI.Tooltip.Tips({
                        tip: {
                            trigger: '.x-icon-error', //出现此样式的元素显示tip
                            alignType: 'top', //默认方向
                            zIndex: 50000,
                            elCls: 'tips tips-warning tips-no-icon tip1',
                            offset: 10 //距离左边的距离
                        }
                    }).render();
                } else {
                    alert(decodeURI(res.msg));
                }
            },
            Error: function (up, err) {
                alert("Error #" + err.code + ": " + err.message);
            }
        }
    });
    uploader.init();
    var uploader2 = new plupload.Uploader({
        runtimes: 'flash',
        browse_button: 'uploadTitleBtn', // you can pass in id...
        //container: document.getElementById('container'), // ... or DOM Element itself
        url: "/FileUpload/AjaxUploadFile",
        filters: {
            max_file_size: '10mb',
            mime_types: [
                { title: "Image files", extensions: "jpg,jpeg,gif,png" }
                //{ title: "Zip files", extensions: "zip,rar" }
            ]
        },
        flash_swf_url: '../../../Areas/Admin/Content/plupload/Moxie.swf',
        //silverlight_xap_url: 'http://rawgithub.com/moxiecode/moxie/master/bin/silverlight/Moxie.cdn.xap',
        init: {
            PostInit: function () {

            },
            FilesAdded: function (up, files) {
                uploader2.start();
                //var file = files[0];
                //var img = new o.Image();
                //img.onload = function () {
                //    img.embed($('#imgdiv')[0], {
                //        width: 100,
                //        height: 60,
                //        crop: true,
                //        swf_url: o.resolveUrl(up.settings.flash_swf_url),
                //        xap_url: o.resolveUrl(up.settings.silverlight_xap_url)
                //    });
                //};
                //img.load(file.getSource());
            },
            UploadProgress: function (up, file) {
                //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
            },
            FileUploaded: function (up, file, info) {
                var res = '{}';
                if (info.response == null) {
                    var headers = info.responseHeaders.split('\r\n');
                    $.each(headers, function (n, item) {
                        if (item && item.split(':')[0] == 'res') {
                            res = eval('(' + item.split(':')[1] + ')');
                        }
                    })
                } else {
                    res = eval('(' + info.response + ')');
                }
                if (res.result == true) {
                    $('#uploadTitleDiv').html('<img src="/File/' + res.id + '" style="width:150px;height:150px" /><input name="Product.TitleImage" type="hidden" value="' + res.id + '" />')
                } else {
                    alert(decodeURI(res.msg));
                }
            },
            Error: function (up, err) {
                alert("Error #" + err.code + ": " + err.message);
            }
        }
    });
    uploader2.init();

    $('#submitBtn').click(function () {
        $('.img-list-des').each(function (n, o) {
            var controls = $(o).find('input,textarea');
            controls.eq(0).attr('name', 'Product.ProdImg[' + n + '].FileName');
            controls.eq(1).attr('name', 'Product.ProdImg[' + n + '].FileID');
            controls.eq(2).attr('name', 'Product.ProdImg[' + n + '].Describe');
            controls.eq(3).attr('name', 'Product.ProdImg[' + n + '].Sort');
        });
        var v = validForm.isValid();
        for (var key in validGroups) {
            if (validGroups[key]) {
                if (!validGroups[key].isValid())
                    v = false;
            }
        }
        if (v) {
            var records = store.getResult();
            var proDiv = $('#ProDiv');
            $.each(records, function (n, record) {
                var _pid = $('<input type="hidden" name="Product.ProductPro[' + n + '].ProID" />');
                _pid.val(record.ProID);
                proDiv.append(_pid);
                var _psort = $('<input type="hidden" name="Product.ProductPro[' + n + '].ProSort" />');
                _psort.val(record.ProSort);
                proDiv.append(_psort);
                var _ptext = $('<input type="hidden" name="Product.ProductPro[' + n + '].ProText" />');
                _ptext.val(record.ProText);
                proDiv.append(_ptext);
                var _pvalue = $('<input type="hidden" name="Product.ProductPro[' + n + '].ProValue" />');
                _pvalue.val(record.ProValue);
                proDiv.append(_pvalue);
            });
        }
        return v;
    })
    if ('@Model.Product.TitleImage' != '') {
        $('#uploadTitleDiv').html('<img src="/File/@Model.Product.TitleImage" style="width:150px;height:150px" /><input name="Product.TitleImage" type="hidden" value="@Model.Product.TitleImage" />')
    }

    var Tab = BUI.Tab
    var tab = new Tab.Tab({
        render: '#tab',
        elCls: 'nav-tabs',
        autoRender: true,
        children: [
          { text: '产品信息', value: '1' },
          { text: '其它属性', value: '2' }
        ]
    });
    tab.on('selectedchange', function (ev) {
        var item = ev.item;
        if (item.get('value') == '1') {
            $('#ProductInfo').show();
            $('#OtherInfo').hide();
            $('#submitDiv').show();
        } else {
            $('#ProductInfo').hide();
            $('#OtherInfo').show();
            $('#submitDiv').hide();
        }
    });
    tab.setSelected(tab.getItemAt(0));
    BUI.use(['bui/calendar', 'bui/extensions/treepicker', 'bui/tree', 'bui/list', 'bui/data', 'bui/toolbar', 'bui/form', 'bui/grid', 'bui/tooltip'], function (Calendar, TreePicker, Tree, List, Data, Toolbar, Form, Grid, Tooltip) {
        $('input,select,textarea').each(function (n, o) {
            if ($(o).attr('datarules')) {
                $(o).attr('data-rules', $(o).attr('datarules'));
                $(o).removeAttr('datarules');
            }
        });
        validForm = new Form.Form({
            srcNode: '#AddForm',
            errorTpl: '<span class="x-icon x-icon-small x-icon-error" data-title="{error}">!</span>'
        }).render();
        $('input,select,textarea').each(function (n, o) {
            if ($(o).attr('data_rules')) {
                $(o).attr('data-rules', $(o).attr('data_rules'));
                $(o).removeAttr('data_rules');
            }
        });
        //data-val
        var addPersonGroup = new Form.Group({ //创建表单分组，此分组不在表单form对象中，所以不影响校验
            srcNode: '#OtherInfo',
            elCls: '',
            errorTpl: '<span class="x-icon x-icon-small x-icon-error" data-title="{error}">!</span>',
            showError: false,
            defaultChildCfg: {
                elCls: ''
            }
        });
        addPersonGroup.render();

        var itemData = eval('@Html.Raw(Model.ProductImgStr)')
        if (itemData && itemData.length > 0) {
            for (var i = 0; i < itemData.length; i++) {
                list.addItem({
                    id: itemData[i].FileID,
                    title: itemData[i].FileName,
                    sort: itemData[i].Sort,
                    href: 'javascript:void(0);',
                    src: '/File/' + itemData[i].FileID,
                    desc: itemData[i].Describe
                });
                $('.img-list-des').last().find('input').last().attr('data-rules', '{required:true,number:true}');
                var valid = new BUI.Form.Group({ //创建表单分组，此分组不在表单form对象中，所以不影响校验
                    srcNode: $('.img-list-des').last(),
                    elCls: '',
                    errorTpl: '<span class="x-icon x-icon-small x-icon-error" data-title="{error}">!</span>',
                    showError: false,
                    defaultChildCfg: {
                        elCls: ''
                    }
                }).render();
                validGroups[itemData[i].FileID] = valid;
                //不使用模板的，左侧显示
                //new BUI.Tooltip.Tips({
                //    tip: {
                //        trigger: '.x-icon-error', //出现此样式的元素显示tip
                //        alignType: 'top', //默认方向
                //        zIndex: 50000,
                //        elCls: 'tips tips-warning tips-no-icon tip1',
                //        offset: 10 //距离左边的距离
                //    }
                //}).render();
            }

        }


        //不使用模板的，左侧显示
        var tips = new Tooltip.Tips({
            tip: {
                trigger: '.x-icon-error', //出现此样式的元素显示tip
                alignType: 'top', //默认方向
                elCls: 'tips tips-warning tips-no-icon tip1',
                offset: 10 //距离左边的距离
            }
        });
        tips.render();

        var treeData = eval('@Html.Raw(Model.ProductClass)');
        //由于这个树，不显示根节点，所以可以不指定根节点
        var tree = new Tree.TreeList({
            nodes: treeData,
            //dirSelectable: false,//阻止树节点选中
            showLine: true //显示连接线
        });

        var picker = new TreePicker({
            width: '360',
            children: [tree] //配置picker内的列表
        });
        var select = new BUI.Select.Select({
            render: '#Product_ClassName',
            width: '360',
            picker: picker,
            forceFit: false, //不强迫列表跟选择器宽度一致
            valueField: '#Product_ClassID'
        });
        select.render();
        tree.on('itemclick', function (ev) {
            if (!ev.item.id)
                return false;
        });

        //-----------------------
        var Store = Data.Store,
        columns = [
            { title: '属性名称', dataIndex: 'ProText', width: 200 }, //editor中的定义等用于 BUI.Form.Field.Text的定义
            { title: '属性值', dataIndex: 'ProValue', width: 200 },
            { title: '排序', dataIndex: 'ProSort', width: 200 },
            {
                title: '操作', width: 100, dataIndex: 'ProID', renderer: function (value, obj) {

                    //if (obj.operation) {//如果是操作行
                    //    return '<a href="#" class="grid-command btn-add"><i class="icon icon-ok"></i> 确认添加</a>'
                    //}
                    return '<a href="javascript:void(0)" class="grid-command btn-edit"><i class="icon icon-edit"></i> 编辑</a>  <a  href="javascript:void(0)" class="grid-command btn-del"><i class="icon icon-trash"></i> 删除</a>'
                }
            }
        ];

        store = new Store({
            data: eval('@Html.Raw(Model.ProductProStr)'),
            autoLoad: true
        }),
        grid = new Grid.SimpleGrid({ //使用简单表格
            render: '#OtherInfoGrid',
            columns: columns,
            tableCls: 'table table-bordered',  //定义表格样式
            width: '100%',
            store: store
        });

        grid.render();
        $('#AddProBtn').click(function () {
            addPersonGroup.valid();
            if (!addPersonGroup.isValid()) {
                return false;
            }
            var data = { ProID: $('#ProID').val(), ProText: $('#ProText').val(), ProValue: $('#ProValue').val(), ProSort: $('#ProSort').val() }
            //新增
            if (data.ProID == '') {
                data.ProID = new Date().getTime();
                var count = store.getCount();
                store.addAt(data, count);
            } else {
                var records = store.getResult();
                $.each(records, function (n, record) {
                    if (record.ProID == data.ProID) {
                        record.ProSort = data.ProSort;
                        record.ProText = data.ProText;
                        record.ProValue = data.ProValue;
                        store.update(record);
                    }
                })
            }
            $('#ProID,#ProText,#ProSort,#ProValue').val('');
        })
        //点击操作
        grid.on('itemclick', function (ev) {
            var sender = $(ev.domTarget),
              itemEl = $(ev.element),
              item = ev.item;
            if (sender.hasClass('btn-del')) { //点击删除操作
                DeleteRecord(item, itemEl);

            } else if (sender.hasClass('btn-edit')) { //点击编辑操作
                EditRecord(item, itemEl);
            }

        });

        function EditRecord(item, itemEl) {
            var record = store.find('ProID', item.ProID);
            $('#ProID').val(record.ProID);
            $('#ProText').val(record.ProText);
            $('#ProSort').val(record.ProSort);
            $('#ProValue').val(record.ProValue);
        }

        function DeleteRecord(item, itemEl) {
            if (confirm('确定删除？')) {
                var record = store.find('ProID', item.ProID);
                store.remove(record);
            }
        }


    });
</script>
